﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DMS.DB;
using DMS.Models;
using System.Data;
using System.Web.Mvc;
using DMS.Extensions;
namespace DMS.BUS
{
    public class Bus
    {
        #region Enums

        public List<SelectListItem> SelectList_BannerType()
        {
            IEnumerable<DMS.Utils.Enums.BannerType> bannerType = Enum.GetValues(typeof(DMS.Utils.Enums.BannerType)).Cast<DMS.Utils.Enums.BannerType>();

            var obj = bannerType.Select(m => new SelectListItem
            {
                Text = Utils.Utils.GetDescriptionFromEnumValue<DMS.Utils.Enums.BannerType>(m),
                Value = ((int)m).ToString()
            }).ToList();

            return obj;
        }

        public List<SelectListItem> SelectList_BannerPosition()
        {
            IEnumerable<DMS.Utils.Enums.BannerPosition> bannerPosition = Enum.GetValues(typeof(DMS.Utils.Enums.BannerPosition)).Cast<DMS.Utils.Enums.BannerPosition>();

            var obj = bannerPosition.Select(m => new SelectListItem
            {
                Text = Utils.Utils.GetDescriptionFromEnumValue<DMS.Utils.Enums.BannerPosition>(m),
                Value = ((int)m).ToString()
            }).ToList();

            return obj;
        }

        public List<SelectListItem> SelectList_DocumentType()
        {
            IEnumerable<DMS.Utils.Enums.DocumentType> documentType = Enum.GetValues(typeof(DMS.Utils.Enums.DocumentType)).Cast<DMS.Utils.Enums.DocumentType>();

            var obj = documentType.Select(m => new SelectListItem
            {
                Text = Utils.Utils.GetDescriptionFromEnumValue<DMS.Utils.Enums.DocumentType>(m),
                Value = ((int)m).ToString()
            }).ToList();

            return obj;
        }

        #endregion

        #region Login
        public AccountObject Login(LoginModel model)
        {
            MainDB _db = new MainDB();
            var salt = Utils.Utils.CreateSalt(model.Username.ToLower().Trim());
            var strPass = Utils.Utils.HashPassword(salt, model.Password);
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Login(model.Username.Trim().ToLower(), strPass);
            _db.Close();
            _db.Dispose();            
            if (dt != null && dt.Rows.Count > 0)
            {
                var obj = new AccountObject
                {
                    Username = dt.Rows[0]["Username"].ToString(),
                    Email = dt.Rows[0]["Email"].ToString(),
                    Avatar = dt.Rows[0]["Avatar"].ToString(),                    
                    Id = Convert.ToInt32(dt.Rows[0]["Id"]),
                    
                };
                _db.Close();
                _db.Dispose();
                return obj;
            }
            return null;
        }

        /// <summary>
        /// Kiem tra thong tin dang nhap
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public bool CheckLogin(string Username, string Password)
        {
            bool flag = true;
            MainDB _db = new MainDB();

            var salt = Utils.Utils.CreateSalt(Username);
            string strPass = Utils.Utils.HashPassword(salt, Password);

            DataTable dt = _db.StoredProcedures.Login(Username.Trim().ToLower(), strPass);
            if (dt == null || dt.Rows.Count == 0)
            {
                flag = false;
            }

            _db.Close();
            _db.Dispose();
            return flag;
        }

        #endregion

        #region Categories

        public List<CategoryObject> GetCatregoryTree()
        {
            var obj = new List<CategoryObject>();
            obj = CategoryRecursion(0, 1);
            return obj;
        }

        public List<CategoryObject> CategoryRecursion(int parentId, int active)
        {
            var obj = Category_Select_by_ParentId(parentId,active);
            var result = new List<CategoryObject>();
            if (obj != null && obj.Count > 0)
            {
                foreach (var item in obj)
                {
                    result.Add(new CategoryObject
                    {
                        CategoryDescription = item.CategoryDescription,
                        CategoryId = item.CategoryId,
                        CategoryName = item.CategoryName,
                        CategoryParentId = item.CategoryParentId,
                        CategoryActive = item.CategoryActive,
                        CategoryChild = CategoryRecursion(item.CategoryId, active)
                    });
                }
            }
            return result;
        }

        public IEnumerable<TreeItem<CategoryObject>> CategoryTree()
        {
            var cats = Category_Select_All(-1);            

            var root = cats.GenerateTree(c => c.CategoryId, c => c.CategoryParentId);

            return root;
        }

        public List<CategoryObject> ReturnCategoryTree(List<CategoryObject> objReturn, IEnumerable<TreeItem<CategoryObject>> categories, int deep = 0)
        {            
            foreach (var c in categories)
            {
                //Console.WriteLine(new String('\t', deep) + c.Item.Name);
                var item = new CategoryObject
                {
                    CategoryId = c.Item.CategoryId,
                    CategoryName = new String('\t', deep) + c.Item.CategoryName,
                    CategoryActive = c.Item.CategoryActive,
                    CategoryDescription = c.Item.CategoryDescription,
                    CategoryParentId = c.Item.CategoryParentId
                };
                objReturn.Add(item);
                ReturnCategoryTree(objReturn, c.Children, deep + 1);
            }

            return objReturn;
        }

        public List<CategoryObject> ReturnCategoryTree()
        {
            var result = new List<CategoryObject>();

            var obj = CategoryTree();

            result = ReturnCategoryTree(result, obj, 0);

            return result;
        }

        public List<CategoryObject> Category_Select_All(int CategoryActive)
        {
            var obj = new List<CategoryObject>();
            MainDB _db = new MainDB();
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Category_Select_All(CategoryActive);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    obj.Add(new CategoryObject
                    {
                        CategoryActive = Convert.ToBoolean(dr["CategoryActive"]),
                        CategoryDescription = dr["CategoryDescription"].ToString(),
                        CategoryName = dr["CategoryName"].ToString(),
                        CategoryParentId = Convert.ToInt32(dr["CategoryParentId"]),
                        CategoryId = Convert.ToInt32(dr["CategoryId"])
                    });
                }
            }

            _db.Close();
            _db.Dispose();
            return obj;
        }

        /// <summary>
        /// Danh sach chuyen muc
        /// </summary>
        /// <param name="ParentId">ParentId = 0: lay tu chuyen mục cha goc</param>
        /// <param name="Active">Active:-1: lấy tất cả; 0-1: lấy theo active</param>
        /// <returns></returns>
        public List<SelectListItem> SelectListCategories(int ParentId, int Active)
        {
            var obj = new List<SelectListItem>();
            obj.Add(new SelectListItem
            {
                Text = "-- Chọn chuyên mục --",
                Value = "0"
            });
            //var cats = Category_Select_by_ParentId(ParentId, Active);
            var cats = ReturnCategoryTree();
            foreach(var item in cats)
            {
                obj.Add(new SelectListItem
                {
                    Text = item.CategoryName.Replace("\t", "-"),
                    Value = item.CategoryId.ToString()
                });
            }
            return obj;
        }
        /// <summary>
        /// Lay danh sach category theo cat parent
        /// </summary>
        /// <param name="CategoryParentId"></param>
        /// <param name="CategoryActive">-1: lay tat ca; 0-1: lay theo trang thai</param>
        /// <returns></returns>
        public List<CategoryObject> Category_Select_by_ParentId(int ParentId, int Active)
        {
            var obj = new List<CategoryObject>();
            MainDB _db = new MainDB();
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Category_Select_by_ParentId(ParentId, Active);
            if(dt!=null && dt.Rows.Count>0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    obj.Add(new CategoryObject
                    {
                        CategoryActive = Convert.ToBoolean(dr["CategoryActive"]),
                        CategoryDescription = dr["CategoryDescription"].ToString(),
                        CategoryName = dr["CategoryName"].ToString(),
                        CategoryParentId = Convert.ToInt32(dr["CategoryParentId"]),
                        CategoryId = Convert.ToInt32(dr["CategoryId"])
                    });
                }
            }
            
            _db.Close();
            _db.Dispose();
            return obj;
        }

        public CategoryObject Category_Select_Id(int ParentId, int Active)
        {
            var obj = new CategoryObject();
            MainDB _db = new MainDB();

            _db.Close();
            _db.Dispose();
            return obj;
        }

        public void Category_Insert(CategoryModel model)
        {
            MainDB _db = new MainDB();
            _db.StoredProcedures.Category_Insert(model.CategoryName, model.CategoryDescription, Convert.ToInt32(model.CategoryParentId), model.CategoryActive);
            _db.Close();
            _db.Dispose();
        }

        public void Category_Update(CategoryModel model)
        {
            MainDB _db = new MainDB();
            _db.StoredProcedures.Category_Update(model.CategoryId, model.CategoryName, model.CategoryDescription, Convert.ToInt32(model.CategoryParentId), model.CategoryActive);
            _db.Close();
            _db.Dispose();
        }

        public CategoryObject Category_Select_by_Id(int CategoryId)
        {
            var objReturn = new CategoryObject();
            MainDB _db = new MainDB();
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Category_Select_by_Id(CategoryId, -1);
            _db.Close();
            _db.Dispose();

            if(dt!=null && dt.Rows.Count>0)
            {
                objReturn = new CategoryObject
                {
                    CategoryActive = Convert.ToBoolean(dt.Rows[0]["CategoryActive"]),
                    CategoryDescription = dt.Rows[0]["CategoryDescription"].ToString(),
                    CategoryName = dt.Rows[0]["CategoryName"].ToString(),
                    CategoryParentId = Convert.ToInt32(dt.Rows[0]["CategoryParentId"]),
                    CategoryId = Convert.ToInt32(dt.Rows[0]["CategoryId"])
                };
            }

            return objReturn;
        }

        #endregion

        #region Documents
        public void Document_Insert(DocumentModel model)
        {
            MainDB _db = new MainDB();

            _db.StoredProcedures.Document_Insert(model.CategoryId, model.DocumentName, model.DocumentCode, model.DocumentDescription, model.DocumentContent, model.DocumentLink, 
                                                model.DocumentImage, model.DocumentType, model.Active, model.Appoved, model.CategoryOther);

            _db.Close();
            _db.Dispose();
        }

        public void Document_Update(DocumentModel model)
        {
            MainDB _db = new MainDB();

            _db.StoredProcedures.Document_Update(model.DocumentId, model.CategoryId, model.DocumentName, model.DocumentCode, model.DocumentDescription, model.DocumentContent, model.DocumentLink,
                                                model.DocumentImage, model.DocumentType, model.Active, model.Appoved, model.CategoryOther);

            _db.Close();
            _db.Dispose();
        }

        public List<DocumentObject> Document_Select_All()
        {
            MainDB _db = new MainDB();
            var objReturn = new List<DocumentObject>();
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Document_Select_All();
            _db.Close();
            _db.Dispose();

            if(dt!=null && dt.Rows.Count>0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    objReturn.Add(new DocumentObject {
                        DocumentCode = dr["DocumentCode"].ToString(),
                        DocumentContent = dr["DocumentCode"].ToString(),
                        DocumentDescription = dr["DocumentDescription"].ToString(),
                        DocumentImage = dr["DocumentImage"].ToString(),
                        DocumentLink = dr["DocumentLink"].ToString(),
                        DocumentName = dr["DocumentName"].ToString(),
                        DocumentType = Convert.ToInt32(dr["DocumentType"].ToString()),
                        CategoryOther = dr["CategoryOther"].ToString(),
                        Active = Convert.ToBoolean(dr["Active"].ToString()),
                        Appoved = Convert.ToBoolean(dr["Appoved"].ToString()),
                        CategoryName = dr["CategoryName"].ToString(),
                        CategoryId = Convert.ToInt32(dr["CategoryId"].ToString()),
                        DocumentId = Convert.ToInt32(dr["DocumentId"].ToString()),
                        CreateDate = Convert.ToDateTime(dr["CreateDate"].ToString()),
                        DocumentTypeName = Utils.Utils.GetDescriptionFromEnumValue<Utils.Enums.DocumentType>(Convert.ToInt32(dr["DocumentType"].ToString()))
                    });
                }
            }

            return objReturn;
        }

        public List<DocumentObject> Document_Select_by_CatId(int CategoryId)
        {
            MainDB _db = new MainDB();
            var objReturn = new List<DocumentObject>();
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Document_Select_by_CatId(CategoryId);
            _db.Close();
            _db.Dispose();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    objReturn.Add(new DocumentObject
                    {
                        DocumentCode = dr["DocumentCode"].ToString(),
                        DocumentContent = dr["DocumentCode"].ToString(),
                        DocumentDescription = dr["DocumentDescription"].ToString(),
                        DocumentImage = string.IsNullOrEmpty(dr["DocumentImage"].ToString()) ? "/assets/fe/css/images/book_1.png" : dr["DocumentImage"].ToString(),
                        DocumentLink = dr["DocumentLink"].ToString(),
                        DocumentName = dr["DocumentName"].ToString(),
                        DocumentType = Convert.ToInt32(dr["DocumentType"].ToString()),
                        CategoryOther = dr["CategoryOther"].ToString(),
                        Active = Convert.ToBoolean(dr["Active"].ToString()),
                        Appoved = Convert.ToBoolean(dr["Appoved"].ToString()),
                        CategoryName = dr["CategoryName"].ToString(),
                        CategoryId = Convert.ToInt32(dr["CategoryId"].ToString()),
                        DocumentId = Convert.ToInt32(dr["DocumentId"].ToString()),
                        CreateDate = Convert.ToDateTime(dr["CreateDate"].ToString()),
                        DocumentTypeName = Utils.Utils.GetDescriptionFromEnumValue<Utils.Enums.DocumentType>(Convert.ToInt32(dr["DocumentType"].ToString()))
                    });
                }
            }

            return objReturn;
        }

        public DocumentObject Document_Select_by_Id(int DocumentId)
        {
            MainDB _db = new MainDB();
            var objReturn = new DocumentObject();
            DataTable dt = new DataTable();
            dt = _db.StoredProcedures.Document_Select_by_Id(DocumentId);
            _db.Close();
            _db.Dispose();

            if (dt != null && dt.Rows.Count > 0)
            {
                objReturn = new DocumentObject
                {
                    DocumentCode = dt.Rows[0]["DocumentCode"].ToString(),
                    DocumentContent = dt.Rows[0]["DocumentContent"].ToString(),
                    DocumentDescription = dt.Rows[0]["DocumentDescription"].ToString(),
                    DocumentImage = dt.Rows[0]["DocumentImage"].ToString(),
                    DocumentLink = dt.Rows[0]["DocumentLink"].ToString(),
                    DocumentName = dt.Rows[0]["DocumentName"].ToString(),
                    DocumentType = Convert.ToInt32(dt.Rows[0]["DocumentType"].ToString()),
                    CategoryOther = dt.Rows[0]["CategoryOther"].ToString(),
                    Active = Convert.ToBoolean(dt.Rows[0]["Active"].ToString()),
                    Appoved = Convert.ToBoolean(dt.Rows[0]["Appoved"].ToString()),
                    //CategoryName = dt.Rows[0]["CategoryName"].ToString(),
                    CategoryId = Convert.ToInt32(dt.Rows[0]["CategoryId"].ToString()),
                    DocumentId = Convert.ToInt32(dt.Rows[0]["DocumentId"].ToString()),
                    CreateDate = Convert.ToDateTime(dt.Rows[0]["CreateDate"].ToString()),
                    DocumentTypeName = Utils.Utils.GetDescriptionFromEnumValue<Utils.Enums.DocumentType>(Convert.ToInt32(dt.Rows[0]["DocumentType"].ToString()))
                };
            }

            return objReturn;
        }
        #endregion

        #region Banners

        public void Banner_Insert(BannerModel model)
        {
            MainDB _db = new MainDB();

            _db.StoredProcedures.Banner_Insert(model.BannerName, model.BannerDescription, model.BannerContent, model.BannerPosition, model.BannerType, model.BannerActive, model.StartDate, model.EndDate);

            _db.Close();
            _db.Dispose();
        }

        public void Banner_Update(BannerModel model)
        {
            MainDB _db = new MainDB();

            _db.StoredProcedures.Banner_Update(model.BannerId, model.BannerName, model.BannerDescription, model.BannerContent, model.BannerPosition, model.BannerType, model.BannerActive, model.StartDate, model.EndDate);

            _db.Close();
            _db.Dispose();
        }

        public List<BannerObject> Banner_Select()
        {
            var obj = new List<BannerObject>();
            DataTable dt = new DataTable();
            MainDB _db = new MainDB();
            dt = _db.StoredProcedures.Banner_Select();
            _db.Close();
            _db.Dispose();
            if(dt!=null && dt.Rows.Count>0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    obj.Add(new BannerObject { 
                        StartDate = Convert.ToDateTime(dr["StartDate"]),
                        EndDate = Convert.ToDateTime(dr["EndDate"]),
                        BannerType = Convert.ToInt32(dr["BannerType"]),
                        BannerPosition = Convert.ToInt32(dr["BannerPosition"]),
                        BannerName = dr["BannerName"].ToString(),
                        BannerId = Convert.ToInt32(dr["BannerId"]),
                        BannerDescription = dr["BannerDescription"].ToString(),
                        BannerContent = dr["BannerContent"].ToString(),
                        BannerActive = Convert.ToBoolean(dr["BannerActive"]),
                        BannerTypeName = Utils.Utils.GetDescriptionFromEnumValue<Utils.Enums.BannerType>(Convert.ToInt32(dr["BannerType"].ToString())),
                        BannerPositionName = Utils.Utils.GetDescriptionFromEnumValue<Utils.Enums.BannerPosition>(Convert.ToInt32(dr["BannerPosition"].ToString())),
                        BannerContentDisplay = Convert.ToInt32(dr["BannerType"]) == (int)Utils.Enums.BannerType.Flash ? string.Format(Utils.Utils.FlashFormatView, dr["BannerContent"].ToString()) : (Convert.ToInt32(dr["BannerType"]) == (int)Utils.Enums.BannerType.Image ? string.Format(Utils.Utils.FlashImageView, dr["BannerContent"].ToString()) : "") 
                    });
                }
            }
            return obj;
        }

        public BannerModel Banner_Select_by_Id(int BannerId)
        {
            var obj = new BannerModel();
            DataTable dt = new DataTable();
            MainDB _db = new MainDB();
            dt = _db.StoredProcedures.Banner_Select_by_Id(BannerId);
            _db.Close();
            _db.Dispose();
            if (dt != null && dt.Rows.Count > 0)
            {
                obj = new BannerModel
                {
                    StartDate = Convert.ToDateTime(dt.Rows[0]["StartDate"]),
                    EndDate = Convert.ToDateTime(dt.Rows[0]["EndDate"]),
                    BannerType = Convert.ToInt32(dt.Rows[0]["BannerType"]),
                    BannerPosition = Convert.ToInt32(dt.Rows[0]["BannerPosition"]),
                    BannerName = dt.Rows[0]["BannerName"].ToString(),
                    BannerId = Convert.ToInt32(dt.Rows[0]["BannerId"]),
                    BannerDescription = dt.Rows[0]["BannerDescription"].ToString(),
                    BannerContent = dt.Rows[0]["BannerContent"].ToString(),
                    BannerActive = Convert.ToBoolean(dt.Rows[0]["BannerActive"]),
                    
                };
            }
            return obj;
        }

        public BannerObject Banner_Select_FE(int BannerPosition)
        {
            var obj = new BannerObject();
            DataTable dt = new DataTable();
            MainDB _db = new MainDB();
            dt = _db.StoredProcedures.Banner_Select_FE(BannerPosition);
            _db.Close();
            _db.Dispose();
            if (dt != null && dt.Rows.Count > 0)
            {
                obj = new BannerObject
                {
                    StartDate = Convert.ToDateTime(dt.Rows[0]["StartDate"]),
                    EndDate = Convert.ToDateTime(dt.Rows[0]["EndDate"]),
                    BannerType = Convert.ToInt32(dt.Rows[0]["BannerType"]),
                    BannerPosition = Convert.ToInt32(dt.Rows[0]["BannerPosition"]),
                    BannerName = dt.Rows[0]["BannerName"].ToString(),
                    BannerId = Convert.ToInt32(dt.Rows[0]["BannerId"]),
                    BannerDescription = dt.Rows[0]["BannerDescription"].ToString(),
                    BannerContent = dt.Rows[0]["BannerContent"].ToString(),
                    BannerActive = Convert.ToBoolean(dt.Rows[0]["BannerActive"]),
                    BannerContentDisplay = Convert.ToInt32(dt.Rows[0]["BannerType"]) == (int)Utils.Enums.BannerType.Flash ? string.Format(Utils.Utils.FlashFormatView, dt.Rows[0]["BannerContent"].ToString()) : (Convert.ToInt32(dt.Rows[0]["BannerType"]) == (int)Utils.Enums.BannerType.Image ? string.Format(Utils.Utils.FlashImageView, dt.Rows[0]["BannerContent"].ToString()) : "") 
                };
            }
            return obj;
        }

        #endregion
    }
}